package com.mar.quarkus.filter;

import cn.hutool.core.util.ReflectUtil;
import org.eclipse.microprofile.jwt.Claims;
import org.eclipse.microprofile.jwt.JsonWebToken;

import javax.enterprise.inject.spi.CDI;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * Description: 反射 .<br>
 *
 * @author m-xy
 *     Created By 2020/4/27 16:31
 */
public class JpaEntityListeners {

    @PrePersist
    public void prePersist(Object entity) {
        ReflectUtil.invoke(entity, "setCreateTime", LocalDateTime.now());
        ReflectUtil.invoke(entity, "setUpdateTime", LocalDateTime.now());
        JsonWebToken context = CDI.current().select(JsonWebToken.class).get();
        if (Objects.nonNull(context)) {
            String username = context.getClaim(Claims.preferred_username.name());
            if (Objects.nonNull(username)) {
                ReflectUtil.invoke(entity, "setCreateBy", username);
                ReflectUtil.invoke(entity, "setUpdateBy", username);
            }
        }
    }

    @PreUpdate
    public void preUpdate(Object entity) {
        ReflectUtil.invoke(entity, "setUpdateTime", LocalDateTime.now());
        JsonWebToken context = CDI.current().select(JsonWebToken.class).get();
        if (Objects.nonNull(context)) {
            String username = context.getClaim(Claims.preferred_username.name());
            if (Objects.nonNull(username)) {
                ReflectUtil.invoke(entity, "setUpdateBy", username);
            }
        }
    }
}
